package com.vinaprime.primeschedule.presentation;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

import com.vinaprime.primeschedule.businesslayer.VPContact_BL;
import com.vinaprime.primeschedule.entities.VPContact;

public class VPContactActivityDetail extends Activity {
	ApplicationInformation appinfo;
	String path;
	VPContact_BL contactBL;
	String[]  _StringId;
	EditText edtVPC_Code ;
	EditText edtVPC_LastName;	
	EditText edtVPC_FirstName ;
	EditText edtVPC_Email;	
	EditText edtVPC_Email1;	
	EditText edtVPC_Email2 ;
	EditText edtVPC_HandPhone ;
	EditText edtVPC_HandPhone1 ;
	EditText edtVPC_HandPhone2 ;
	EditText edtVPC_HomePhone ;
	EditText edtVPC_HomePhone1 ;
	EditText edtVPC_HomePhone2 ;
	EditText edtVPC_Decription ;
	ImageView imgContact;
	Switch swtchange ;
	String path_image;
	String file_name;
	Uri imageCaptureUri;
	byte[] imagebyte = null;
	private static final int IMAGE_CAPTURE =1;
	private static final int IMAGE_SELECT =2;	
	private static final int IMAGE_CROP_FROM_CAMERA = 3;
	@SuppressLint("newAPI")
	@Override	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		setContentView(R.layout.activity_vpcontact_detail);
		ActionBar actionBar = getActionBar();
		Drawable d=getResources().getDrawable(R.raw.background_top);  
		actionBar.setBackgroundDrawable(d);
			//--------------------//
			//Lay tra tri truyen qua, de xac dinh la them moi hay xem thong tin
			Intent intent = getIntent();		
		    _StringId = intent.getStringArrayExtra(VPContactActivity.CONTACT_ID);
			appinfo = new ApplicationInformation(this);
			path = appinfo.getDBPath();
			contactBL = new VPContact_BL(this, path+"databases/")	;
			edtVPC_Code = (EditText)findViewById(R.id.edttext_MaContact);	
			edtVPC_LastName = (EditText)findViewById(R.id.edttext_HovaLot);
			edtVPC_FirstName = (EditText)findViewById(R.id.edttext_Ten);	
			edtVPC_Email = (EditText)findViewById(R.id.edttext_Email);	
			edtVPC_Email1 = (EditText)findViewById(R.id.edttext_Email2);	
			edtVPC_Email2 = (EditText)findViewById(R.id.edttext_Email3);	
			edtVPC_HandPhone = (EditText)findViewById(R.id.edttext_Didong);
			edtVPC_HandPhone1 = (EditText)findViewById(R.id.edttext_Didong2);	
			edtVPC_HandPhone2 = (EditText)findViewById(R.id.edttext_Didong3);	
			edtVPC_HomePhone = (EditText)findViewById(R.id.edttext_SoDtNha);
			edtVPC_HomePhone1 = (EditText)findViewById(R.id.edttext_SoDtNha2);	
			edtVPC_HomePhone2 = (EditText)findViewById(R.id.edttext_SoDtNha3);	
			edtVPC_Decription = (EditText)findViewById(R.id.edttext_GhiChu);
			swtchange = (Switch)findViewById(R.id.switch_Active);
			//byte[] imagebyte = null;
			imgContact = (ImageView)findViewById(R.id.imgContact);
			//view contact image context
			imgContact.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
					// TODO Auto-generated method stub
					registerForContextMenu(imgContact);
					return false;
				}
			});
		
			if (_StringId[0].equals("VIEW")){ 
		
					
					VPContact contact = new VPContact();
					contact =  contactBL.getContactbyID(Integer.parseInt(_StringId[1].toString()));
		
					//code					
					edtVPC_Code.setText(contact.getVpcCode());
					edtVPC_Code.setFocusable(false);
					
					//First Name					
					edtVPC_LastName.setText(contact.getVpcLastName());				
					edtVPC_LastName.setFocusable(false);
					//Last Name					
					edtVPC_FirstName.setText(contact.getVpcFistName());
					edtVPC_FirstName.setFocusable(false);
					//Email								
					edtVPC_Email.setText(contact.getVpcEmail());
					edtVPC_Email.setFocusable(false);
					//Toast.makeText(getApplicationContext(), "TEST:"+contact.getVpcEmail1(),Toast.LENGTH_SHORT).show();
					/*Toast.makeText(getApplicationContext(), contact.getVpcEmail1()+"e1:"
					+ contact.getVpcEmail1().toString() +"e2:"
					+ contact.getVpcEmail2().toString() 
					, Toast.LENGTH_SHORT).show();*/
					//Email1						
					edtVPC_Email1.setText(contact.getVpcEmail1());
					edtVPC_Email1.setFocusable(false);
								
					//Email2		
					edtVPC_Email2.setText(contact.getVpcEmail2());
					edtVPC_Email2.setFocusable(false);
					
					//HandPhone					
					edtVPC_HandPhone.setText(contact.getVpcHandPhone());
					edtVPC_HandPhone.setFocusable(false);
										
					//HandPhone1										
					edtVPC_HandPhone1.setText(contact.getVpcHandPhone1());
					edtVPC_HandPhone1.setFocusable(false);
					
					//HandPhone2								
					edtVPC_HandPhone2.setText(contact.getVpcHandPhone2());
					edtVPC_HandPhone2.setFocusable(false);
					
					//HomePhone
					edtVPC_HomePhone.setText(contact.getVpcHomePhone());
					edtVPC_HomePhone.setFocusable(false);
									
					//HomePhone1					
					edtVPC_HomePhone1.setText(contact.getVpcHomePhone1());
					edtVPC_HomePhone1.setFocusable(false);
					
					//HomePhone2								
					edtVPC_HomePhone2.setText(contact.getVpcHomePhone2());
					edtVPC_HomePhone2.setFocusable(false);
					
					//Description									
					edtVPC_Decription.setText(contact.getVpcDescription());
					edtVPC_Decription.setFocusable(false);
					//ENABLE fLAG
					String _status = contact.getVpcEnableFlag();					
					swtchange.setFocusable(false);
					if (_status.equals("Y")){
						swtchange.setChecked(true)  ;
						
					}else
					{
						swtchange.setChecked(false)  ;
					}
					//read image from blob file. Decode byte[] 
					if (contact.getVpcImage()!= null) {
						imagebyte = contact.getVpcImage();
						imgContact.setImageBitmap(BitmapFactory.decodeByteArray(imagebyte, 0, imagebyte.length));
					} 
					imgContact.setFocusable(false);	
					imgContact.setLongClickable(false);
										
			}
			else if (_StringId[0].equals("EDIT")){				
				VPContact contact = new VPContact();
				contact =  contactBL.getContactbyID(Integer.parseInt(_StringId[1]));
		//		Toast.makeText(getApplicationContext(), "id truyen:"+_intId+"id"+contact.getVpcID()+" name:"+ contact.getVpcFistName().toString(), Toast.LENGTH_SHORT).show();
				//code				
				edtVPC_Code.setText(contact.getVpcCode());
				
				//First Name				
				edtVPC_LastName.setText(contact.getVpcLastName());
				
				//Last Name				
				edtVPC_FirstName.setText(contact.getVpcFistName());
				
				//Email
				edtVPC_Email.setText(contact.getVpcEmail());
				//Email1
				edtVPC_Email1.setText(contact.getVpcEmail1());
							
				//Email2													
				edtVPC_Email2.setText(contact.getVpcEmail2());
				
				//HandPhone				
				edtVPC_HandPhone.setText(contact.getVpcHandPhone());
									
				//HandPhone1								
				edtVPC_HandPhone1.setText(contact.getVpcHandPhone1());
				
				//HandPhone2								
				edtVPC_HandPhone2.setText(contact.getVpcHandPhone2());
				
				//HomePhone				
				edtVPC_HomePhone.setText(contact.getVpcHomePhone());
								
				//HomePhone1				
				edtVPC_HomePhone1.setText(contact.getVpcHomePhone1());
				
				//HomePhone2							
				edtVPC_HomePhone2.setText(contact.getVpcHomePhone2());
				
				//Description								
				edtVPC_Decription.setText(contact.getVpcDescription());
				//enable_flag
				//ENABLE fLAG
				String _status = contact.getVpcEnableFlag();					
			
				if (_status.equals("Y")){
					swtchange.setChecked(true)  ;
					
				}else
				{
					swtchange.setChecked(false)  ;
				}
				//read image from blob file. Decode byte[] 
				if (contact.getVpcImage()!= null) {
					imagebyte = contact.getVpcImage();
					imgContact.setImageBitmap(BitmapFactory.decodeByteArray(imagebyte, 0, imagebyte.length));
				} 				
			}
			else
			{
				//Toast.makeText(getApplicationContext(), _StringId[0].toString()+"aaaaaa:"+_StringId[1].toString(), Toast.LENGTH_SHORT).show();
			};		
	
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.vpcontact_activity_detail, menu);
		return true;
	}
	public void btnHuy(View v){
		this.finish();
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
	}
	@Override
	  public boolean onOptionsItemSelected(MenuItem item) {
		String _status ;
		//Toast.makeText(getApplicationContext(),_StringId[0], Toast.LENGTH_SHORT).show();
    	if (swtchange.isChecked())
    		_status = "Y";
		else
			_status = "N";		
		switch (item.getItemId()) {
	    case R.id.action_save:
	    	//get status 
	    	
	    	
	    //  Toast.makeText(this, "Menu Save selected", Toast.LENGTH_SHORT).show();    
			if (_StringId[0].equals("EDIT")){
				VPContact mycontact = new VPContact(
						Integer.parseInt(_StringId[1]),//contactBL.getNewContactId(), 
						edtVPC_Code.getText().toString(), 
						edtVPC_LastName.getText().toString(),
						edtVPC_FirstName.getText().toString(), 
						
						edtVPC_Email.getText().toString(), 
						edtVPC_Email1.getText().toString(), 
						edtVPC_Email2.getText().toString(), 
						
						edtVPC_HandPhone.getText().toString(), 
						edtVPC_HandPhone1.getText().toString(), 
						edtVPC_HandPhone2.getText().toString(), 
						
						edtVPC_HomePhone.getText().toString(), 
						edtVPC_HomePhone1.getText().toString(), 
						edtVPC_HomePhone2.getText().toString(),
						
						edtVPC_Decription.getText().toString(), 
						_status,
						imagebyte);						
				contactBL.updateContact(mycontact);
				
				Intent intentFatherGroup = new Intent();
		    	//intentFatherGroup.putExtra(CONTACT_LIST_CHECK, _listSend);
				setResult(5,intentFatherGroup);
			   	finish();
				//Toast.makeText(getApplicationContext(), "Save Edit  : " + _StringId[0], Toast.LENGTH_SHORT).show();
				//System.out.print("Save Edit  : " +imagebyte);
		
			} else if (_StringId[0].equals("VIEW")){
				Toast.makeText(getApplicationContext(), "Not save at view status", Toast.LENGTH_SHORT).show();
			}
			else {
			VPContact mycontact = new VPContact(
						contactBL.getNewContactId(), 
						edtVPC_Code.getText().toString(), 
						edtVPC_LastName.getText().toString(),
						edtVPC_FirstName.getText().toString(), 
						
						edtVPC_Email.getText().toString(), 
						edtVPC_Email1.getText().toString(), 
						edtVPC_Email2.getText().toString(), 
						
						edtVPC_HandPhone.getText().toString(), 
						edtVPC_HandPhone1.getText().toString(), 
						edtVPC_HandPhone2.getText().toString(), 
						
						edtVPC_HomePhone.getText().toString(), 
						edtVPC_HomePhone1.getText().toString(), 
						edtVPC_HomePhone2.getText().toString(),
						
						edtVPC_Decription.getText().toString(), 
						_status,
						imagebyte);							
				contactBL.addContact(mycontact);
				//System.out.print("Save Them  : " +imagebyte);
				Intent intentFatherGroup = new Intent();
		    	//intentFatherGroup.putExtra(CONTACT_LIST_CHECK, _listSend);
				setResult(5,intentFatherGroup);
			   	finish();
			}
			
			break;
	    case R.id.action_cancel:
	     // Toast.makeText(this, "Menu Cancel selected", Toast.LENGTH_SHORT) .show();
	        this.finish();
	      break;

	    default:
	      break;
	    }

	    return true;
	  } 	
	public void onSwitchChange(View v){	
		
		final Switch swtchange = (Switch)findViewById(R.id.switch_Active);	
		swtchange.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean ischeck) {
				// TODO Auto-generated method stub
				if (ischeck) {
				//	swtchange.setTextOn(R.string.switch_on);
				}else{
					//swtchange.setTextOn(R.string.switch_off);
				}
			}
		});	}
	@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
			 ContextMenuInfo menuInfo) {
			 // TODO Auto-generated method stub
			 super.onCreateContextMenu(menu, v, menuInfo);
			 getMenuInflater()
			 .inflate(R.menu.vpcontact_detail_context, menu);
			 menu.setHeaderTitle(R.string.ctx_title_image);
			 }
	@Override
	 public boolean onContextItemSelected(MenuItem item) {
		switch(item.getItemId())
		 {
		 case R.id.ctx_album:				   
			// Toast.makeText(getApplicationContext(), "Context Album", Toast.LENGTH_SHORT).show();
			 startAlbum();
		 break;		
		 case R.id.ctx_capture:				   
			// Toast.makeText(getApplicationContext(), "Context Camera", Toast.LENGTH_SHORT).show();
			 startCamera();
		 break;		
		 case R.id.ctx_delete_image:				   
			// Toast.makeText(getApplicationContext(), "Context Change", Toast.LENGTH_SHORT).show();
			 if (imagebyte != null){
				 imagebyte = null;
				 imgContact.setImageResource(R.raw.user1);
			 }
		 break;	
		 default:
			 break;
		 
		 }
		 return super.onContextItemSelected(item);		
 }
	//start camera
	public void startCamera()
	{
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		imageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
				   "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
		
		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageCaptureUri);
		try{
			intent.putExtra("return-data", true);		
			startActivityForResult(intent, IMAGE_CAPTURE);
		//Toast.makeText(getApplicationContext(), path_image+ ""+file_name, Toast.LENGTH_SHORT).show();
		} catch (ActivityNotFoundException e)
		{
			e.printStackTrace();
		}
	}
	// start select album
	public void startAlbum()
	{
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select picture"), IMAGE_SELECT);	
	}
	//Get value from camera, album
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		System.out.println("requestcode" + requestCode + "result code " + requestCode + "intentt" + data);
		imgContact = (ImageView)findViewById(R.id.imgContact);
		super.onActivityResult(requestCode, resultCode, data);	
		if (resultCode==RESULT_OK)
		{					
				if (requestCode == IMAGE_SELECT){	
					 imageCaptureUri = data.getData();
					 doCrop();
					
				}				
				else if (requestCode == IMAGE_CAPTURE){
					
					System.out.println("IMAGE CAPTUR requestcode" + requestCode + "result code " + requestCode + "intentt" + data);
					 doCrop();
					
					}
				else if (requestCode == IMAGE_CROP_FROM_CAMERA){
					System.out.println("IMAGE_CROP_FROM_CAMERA requestcode" + requestCode + "result code " + requestCode + "intentt" + data);
					Bundle extra = data.getExtras();
					if (extra!=null){
						Bitmap photo = extra.getParcelable("data");
						imagebyte = null;
						imgContact.setImageBitmap(photo);	
						imagebyte = getImageByte(photo);
						
					}
					
						File f = new File(imageCaptureUri.getPath());
						if (f.exists()) f.delete();
					
					
				}
				else{
					return;
					
				}
		}
		else if (resultCode==RESULT_CANCELED){
			return ;		
			//Toast.makeText(getApplicationContext(), "Cancel!"  , Toast.LENGTH_SHORT).show();
		}
		
	}

	private void doCrop() {
		// TODO Auto-generated method stub
		final ArrayList<CropOption> cropoption =  new ArrayList<CropOption>();
		Intent  intent  = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");
		List<ResolveInfo> list  =  getPackageManager().queryIntentActivities(intent, 0);
		int size =  list.size();
		if (size == 0 ){
			Toast.makeText(getApplicationContext(), "Can't find image crop app!"  , Toast.LENGTH_SHORT).show();
			return;
		}else{
			intent.setData(imageCaptureUri);
			intent.putExtra("outputX", 250);
			intent.putExtra("outputY", 250);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			intent.putExtra("return-data", true);
			if (size ==1){
				Intent i = new Intent(intent);
				ResolveInfo res =  list.get(0)	;
				i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
				startActivityForResult(i, IMAGE_CROP_FROM_CAMERA);
			}else
			{
				for (ResolveInfo res:list)
				{
					final CropOption crop =  new CropOption();
					crop.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
					crop.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
					crop.appIntent = new Intent(intent);
					
					crop.appIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
					cropoption.add(crop);
				}
				CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropoption);
				AlertDialog.Builder diag =  new AlertDialog.Builder(this);
				diag.setTitle("Choose Crop App");
				diag.setAdapter(adapter, new DialogInterface.OnClickListener() {	
					public void onClick(DialogInterface dialog, int position) {
						// TODO Auto-generated method stub
						startActivityForResult(cropoption.get(position).appIntent, IMAGE_CROP_FROM_CAMERA);
					}
				});
				diag.setOnCancelListener(new DialogInterface.OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						// TODO Auto-generated method stub
						if (imageCaptureUri != null){
							getContentResolver().delete(imageCaptureUri, null, null);
							imageCaptureUri = null;
						}
					}
				});
				  AlertDialog alert = diag.create();
			        
			        alert.show();
			}
		}
			
	}
		
//chua su dung
	private String getPathFromCamera(Uri selectimageUri2) {
		// TODO Auto-generated method stub
		try
		{
			String [] filePathColumn = {MediaStore.Images.Media.DATA};
			Cursor cur = getContentResolver().query(selectimageUri2, filePathColumn, null, null, null);
			cur.moveToFirst();
			int colunmindex = cur.getColumnIndexOrThrow(filePathColumn[0]);
			String filepath = cur.getString(colunmindex);
			Log.v("log","filePath is : "+filepath); 		
			return filepath;
		}
		catch (Exception e)
		{
			return selectimageUri2.getPath();
		}
	}
//chua su dung
	@SuppressWarnings("deprecation")
	private String getPath(Uri selectimageUri) {
		// TODO Auto-generated method stub
		try
		{
		String [] dataimage = {MediaStore.Images.Media.DATA};
		Cursor cur  = managedQuery(selectimageUri, dataimage, null, null, null);
		int columnindex =  cur.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cur.moveToFirst();
		return cur.getString(columnindex);
		} catch (Exception e){
			return selectimageUri.getPath();
		}
	
	}
/// chuyen tu bitmap sang byte	
	private byte[] getImageByte(Bitmap bitmap){
		byte [] imageByte = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream(); 		
		try{			
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
			imageByte = baos.toByteArray();
		} catch (Exception e){
			
		}		
		return imageByte;
	}
}
